package com.kfm.web.security;

import com.alibaba.fastjson.JSON;
import com.kfm.common.domain.response.Result;
import com.kfm.common.exception.ServerException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于处理认证过程中出现的异常。
 * 如：未登录访问受保护的资源时，会抛出异常，此时就会调用该类的 commence 方法
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException, ServerException {
        response.setHeader("content-type", "application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(Result.failure("请先登录", 401)));
    }
}
